//
//  BLRechargeOnlineViewController.m
//  blanket
//
//  Created by Mac on 2017/12/6.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "BLRechargeOnlineViewController.h"
#import "BLRechargePayViewController.h"
#import "BLPayModel.h"
@interface BLRechargeOnlineViewController ()
@property(nonatomic, strong) STButton                     *moneyButton;
@property(nonatomic, strong) UITextField                     *textFiled;
@property(nonatomic, strong) NSMutableArray                     *butonArray;
@property(nonatomic, strong) NSMutableArray<BLPayModel*>                     *dataSouce;
@end

@implementation BLRechargeOnlineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"线上充值";
    [self sendFecthPayListRequest];
    // Do any additional setup after loading the view.
}
#pragma mark --subView
- (void)configSubView{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    header.backgroundColor = [UIColor whiteColor];
    self.moneyButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 44)
                                                 title:[NSString stringWithFormat:@"当前盖币%@",self.userModel.balance]
                                            titleColor:BL_redColor
                                             titleFont:14
                                          cornerRadius:0
                                       backgroundColor:BL_backgroundColor
                                       backgroundImage:nil
                                                 image:[UIImage imageNamed:@"通知"]];
    self.moneyButton.imageEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    self.moneyButton.titleEdgeInsets = UIEdgeInsetsMake(0, 25, 0, 0);
    [header addSubview:self.moneyButton];
    
    UIView * titleView = [self headerViewWithTitle:@"请选择充值金额"];
    titleView.top = self.moneyButton.bottom;
    [header addSubview:titleView];
    
    self.textFiled = [[UITextField alloc] initWithFrame:CGRectMake(15, titleView.bottom, 300, 30)];
    self.textFiled.placeholder = @"请输入金额";
    self.textFiled.keyboardType = UIKeyboardTypeNumberPad;
    [header addSubview:self.textFiled];
    CGFloat top = self.textFiled.bottom + 20;
    CGFloat defultLeft = 20;
    self.butonArray = [NSMutableArray new];
    for (NSInteger i = 1; i <= self.dataSouce.count;i++) {
        BLPayModel * model = self.dataSouce[i-1];
        NSString * money = model.price;
       // NSInteger  all = model.price.floatValue + model.grade.floatValue;
        NSInteger  all = model.grade.integerValue;
        NSString *   score = model.score;
        
        if ((i%2) == 1) {
            defultLeft = 20;
        }else{
            defultLeft = UIScreenWidth - 20 - ((UIScreenWidth - 60)/2);
        }
        
        STButton *button1 = [self defultButtonWithTitle:[NSString stringWithFormat:@"%@元",money]
                                               subTitle:[NSString stringWithFormat:@"送%ld盖币 + %@积分",
                                                         all,score]];
        button1.left = defultLeft;
        button1.top = top;
        [header addSubview:button1];
        
        NSInteger row = i / 2;
        if (row) {
           top =  row * button1.height + row * 20 + self.textFiled.bottom + 20;
        }
        [self.butonArray addObject:button1];
    }
    __weak typeof(self) weakSelf =  self;
    STButton * confimButton = [[STButton alloc] initWithFrame:CGRectMake(30, 0, UIScreenWidth - 60, 44)
                                                        title:@"立即充值"
                                                   titleColor:[UIColor whiteColor]
                                                    titleFont:18
                                                 cornerRadius:5
                                              backgroundColor:BL_BlueBackGroundColor
                                              backgroundImage:nil
                                                        image:nil];
    [confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedCommitButton];
    }];
    confimButton.top = top + 50  + 30;
    confimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [header addSubview:confimButton];
    
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, confimButton.bottom + 100, 80, 80)];
    imageView.centerX = UIScreenWidth / 2;
    imageView.image = [UIImage imageNamed:@"底图logo"];
    [header addSubview:imageView];
    header.height = UIScreenHeight;
    self.tableView.tableHeaderView = header;
    [self.tableView reloadData];
}
- (UIView*)headerViewWithTitle:(NSString*)title{
    UIView * sectionHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 44)];
    sectionHeader.backgroundColor = [UIColor whiteColor];
    STButton * line = [[STButton alloc] initWithFrame:CGRectMake(15, 0, 4, 22)
                                                title:nil
                                           titleColor:nil
                                            titleFont:14
                                         cornerRadius:0
                                      backgroundColor:BL_BlueBackGroundColor
                                      backgroundImage:nil
                                                image:nil];
    line.centerY = 22;
    [sectionHeader addSubview:line];
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(line.right + 20, 0, 200, 44)
                                                     text:title
                                                textColor:BL_firstTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    
    [sectionHeader addSubview:titleLable];
    return sectionHeader;
}
- (STButton*)defultButtonWithTitle:(NSString*)title subTitle:(NSString*)subtitle{
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(20, 0, (UIScreenWidth - 60)/2, 50)
                                                     title:[NSString stringWithFormat:@"%@\n%@",title,subtitle]
                                                titleColor:BL_redColor
                                                 titleFont:12
                                              cornerRadius:5
                                           backgroundColor:[UIColor whiteColor]
                                           backgroundImage:nil
                                                     image:nil];
    buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    buyButton.titleLabel.numberOfLines = 0;
    __weak typeof(self) weakSelf =  self;
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedMenuButton:sender];
    }];
    [buyButton setAttributedTitle:[buyButton.currentTitle st_convertAttributeStringWithKeyWord:title attributes:@{NSForegroundColorAttributeName:BL_firstTextColor}] forState:UIControlStateNormal];
    [buyButton st_setBorderWith:1 borderColor:BL_lineColor cornerRadius:5];
    return buyButton;
}
- (void)configButtonMoney{
    NSArray * array = [self.dataSouce subarrayWithRange:NSMakeRange(0, self.butonArray.count)];
    for (NSInteger i = 0; i < self.butonArray.count; i ++) {
        BLPayModel * model = self.dataSouce[i];
        UIButton * button = self.butonArray[i];
        
        NSString * title = [NSString stringWithFormat:@"%@元",model.price];
        
        //NSString * give = @(model.grade.integerValue + model.price.integerValue).description;
        NSString * give = @(model.grade.integerValue).description;
        NSString * subtitle = [NSString stringWithFormat:@"送%@+%@积分",give,model.score];
        
        [button setTitle:[NSString stringWithFormat:@"%@\n%@",title,subtitle] forState:UIControlStateNormal];
        [button setAttributedTitle:[button.currentTitle st_convertAttributeStringWithKeyWord:title attributes:@{NSForegroundColorAttributeName:BL_firstTextColor}] forState:UIControlStateNormal];
    }
}
- (BLPayModel*)findSlectedModel{
    for (NSInteger i = 0; i < self.butonArray.count; i ++) {
        UIButton * button = self.butonArray[i];
        if (button.selected) {
            BLPayModel * model = self.dataSouce[i];
            return model;
        }
    }
    return nil;
}
#pragma mark --Action Method
- (void)onSlectedMenuButton:(UIButton*)sender{
    for (UIButton * button in self.butonArray) {
        
        if (button == sender) {
            sender.selected = !sender.selected;
            
        }else{
           button.selected = NO;
        }
        if (button.selected) {
            [button st_setBorderWith:1 borderColor:BL_BlueBackGroundColor cornerRadius:5];
        }else{
            button.backgroundColor = [UIColor whiteColor];
            [button st_setBorderWith:1 borderColor:BL_lineColor cornerRadius:5];
        }
    }
}
- (void)onSelectedCommitButton{
    BLPayModel * model = [self findSlectedModel];
    if (!self.textFiled.text.length && !model) {
        [SVProgressHUD showErrorWithStatus:@"您还未输入金额"];
        return;
    }

    NSMutableDictionary * dic =  [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    
    if (model) {
        [dic setObject:@"1" forKey:@"type"];
        [dic setObject:model.price forKey:@"price"];
        [dic setObject:model.score forKey:@"score"];
        [dic setObject:model.grade forKey:@"grade"];
        [dic setObject:@"1" forKey:@"recharge_type"];
    }else if (self.textFiled.text.length){
        [dic setObject:@"2" forKey:@"type"];
        [dic setObject:self.textFiled.text forKey:@"price"];
        [dic setObject:@"0" forKey:@"score"];
        [dic setObject:@"0" forKey:@"grade"];
        [dic setObject:@"2" forKey:@"recharge_type"];
    }
    
    BLRechargePayViewController * vc = [BLRechargePayViewController new];
    vc.moneyStr = self.textFiled.text;
    vc.paramDic = dic;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --NetWork Method
- (NSString*)fetchOrderID{
    return @"2017122710255575";
}
- (void)wechatPay{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    // [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Weipay/weixin_pay"];
    NSString * orderID = [self fetchOrderID];
    if (orderID.length) {
        [dic setObject:orderID forKey:@"order"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString)
                                                 //wechat
                                                 PayReq *request = [PayReq new];
                                                 request.nonceStr = dataDic[@"noncestr"];
                                                 request.package = dataDic[@"package"];
                                                 request.partnerId = dataDic[@"partnerid"];
                                                 request.prepayId = dataDic[@"prepayid"];
                                                 request.sign = dataDic[@"sign"];
                                                 request.timeStamp = [dataDic[@"timestamp"] intValue];
                                                 [WXApi sendReq:request];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}

- (void)sendFecthPayListRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/rechargeConfAction"];
    //    if ([STUserManger defult].userID.length) {
    //        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    //    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSArray * dataArray =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 self.dataSouce = [NSMutableArray new];
                                                 for (NSDictionary * modelDic in dataArray) {
                                                     BLPayModel * model = [BLPayModel mj_objectWithKeyValues:modelDic];
                                                     [self.dataSouce addObject:model];
                                                 }
                                                 [self configSubView];
                                                //[self configButtonMoney];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end

